import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../../../prisma/prisma.server';
import { createData, deleteType, getList, updateData } from './dict_type.dto';
import { getUser } from 'src/utils/getUser';
import { nowDateTime } from '../../../utils/';
import { redisUtils } from '../../../utils/redis';

@Injectable()
export class DictTypeService {
  constructor(private readonly prisma: PrismaService) {}

  // 新增字典类型
  async createDictType(
    { dictName, dictType, status, remark }: createData,
    token: string,
  ) {
    const key = 'dictTypeList:all';
    await redisUtils.del(key);
    const user = await getUser(token);
    const currentTime = nowDateTime();
    const { count } = await this.prisma.sysDictType.createMany({
      data: {
        dictName,
        dictType,
        status: Boolean(status),
        remark,
        createBy: user,
        createTime: currentTime,
      },
    });
    return count;
  }

  // 修改字典类型
  async updateDictType(
    { dictId, dictName, dictType, status, remark }: updateData,
    token: string,
  ) {
    const dictTypeKey = `dictType:${dictId}`; // 单条数据缓存 Key
    const dictTypeListKey = 'dictTypeList:all'; // 全部数据缓存 Key
    await redisUtils.del(dictTypeKey);
    await redisUtils.del(dictTypeListKey);
    const user = await getUser(token);
    const currentTime = nowDateTime();
    const { count } = await this.prisma.sysDictType.updateMany({
      data: {
        dictName,
        dictType,
        status: Boolean(status),
        remark,
        updateBy: user,
        updateTime: currentTime,
      },
      where: { dictId },
    });
    return count;
  }

  // 查询字典类型详细
  async getDictType(dictId: number) {
    const dictTypeKey = `dictType:${dictId}`; // 单条数据缓存 Key
    const dictTypeListKey = 'dictTypeList:all'; // 全部数据缓存 Key

    // 尝试从单条数据缓存中获取
    const redisData = JSON.parse(await redisUtils.get(dictTypeKey));
    if (redisData) return redisData;

    // 尝试从所有数据缓存中获取
    const redisListData = JSON.parse(await redisUtils.get(dictTypeListKey));
    if (redisListData) {
      // 在缓存的所有数据中查找目标数据
      const data = redisListData.find((v) => v.dictId === dictId);
      if (data) {
        // 将单条数据缓存以便下次直接获取
        await redisUtils.set(dictTypeKey, JSON.stringify(data));
        return data;
      }
    }

    // 如果缓存中没有，则从数据库查询所有数据并缓存
    const dbData = await this.prisma.sysDictType.findMany();
    const formattedData = dbData.map((v) => ({
      ...v,
      status: Number(v.status),
    }));

    // 更新缓存的所有数据
    await redisUtils.set(dictTypeListKey, JSON.stringify(formattedData));

    // 查找目标数据
    const targetData = formattedData.find((v) => v.dictId === dictId);
    if (targetData) {
      // 缓存单条数据
      await redisUtils.set(dictTypeKey, JSON.stringify(targetData));
    }

    return targetData || null; // 如果数据不存在则返回 null
  }

  // 查询字典类型列表
  async findAll({ pageNum, pageSize }: getList) {
    const key = `dictTypeList:all`;
    const startIndex = (pageNum - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const redisData = JSON.parse(await redisUtils.get(key));
    if (redisData) {
      const total = redisData.length; // 从 Redis 数据中获取总数
      return {
        rows: redisData.slice(startIndex, endIndex),
        total,
      };
    }
    // 从数据库获取数据
    const data = (await this.prisma.sysDictType.findMany()).map((v) => ({
      ...v,
      status: Number(v.status),
    }));
    // 将数据存储到 Redis
    await redisUtils.set(key, JSON.stringify(data));
    const total = data.length; // 获取总数
    return {
      rows: data.slice(startIndex, endIndex),
      total,
    };
  }

  // 获取字典选择框列表
  async optionselect() {
    const key = `dictTypeList:all`;
    const redisData = JSON.parse(await redisUtils.get(key));
    if (redisData) {
      return {
        rows: redisData,
        total: redisData.length, // 获取总数
      };
    }
    const rows = (await this.prisma.sysDictType.findMany()).map((v) => ({
      ...v,
      status: Number(v.status),
    }));
    await redisUtils.set(key, JSON.stringify(rows));
    return {
      rows,
      total: rows.length, // 获取总数
    };
  }

  // 删除字典类型
  async deleteDictType({ dictIds }: deleteType) {
    const dictTypeListKey = 'dictTypeList:all'; // 全部数据缓存 Key
    // 删除每个字典类型的缓存
    for (const dictId of dictIds) {
      const dictTypeKey = `dictType:${dictId}`; // 单条数据缓存 Key
      await redisUtils.del(dictTypeKey);
    }
    // 删除全部数据的缓存
    await redisUtils.del(dictTypeListKey);
    // 删除数据库中的字典类型
    const { count } = await this.prisma.sysDictType.deleteMany({
      where: { dictId: { in: dictIds } },
    });
    return count;
  }

  //刷新字典缓存
  async refreshCache(): Promise<number> {
    return new Promise(async (resolve, reject) => {
      try {
        const dictTypeListKey = 'dictTypeList:all'; // 缓存的 Key
        const data = (await this.prisma.sysDictType.findMany()).map((v) => ({
          ...v,
          status: Number(v.status),
        }));
        await redisUtils.set(dictTypeListKey, JSON.stringify(data));
        for (const item of data) {
          const dictTypeKey = `dictType:${item.dictId}`;
          await redisUtils.del(dictTypeKey);
        }
        resolve(1);
      } catch (error) {
        reject(0);
      }
    });
  }
}
